package com.boot.ys.mybatisplus.listener;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.boot.ys.mybatisplus.entity.Easyexcel;
import com.boot.ys.mybatisplus.service.EasyexcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 这个类是用来读取EasyExcel接口
 */
@Slf4j
public class EasyExcelListener extends AnalysisEventListener<Easyexcel> {


    @Autowired
    private EasyexcelService easyexcelService;

    //无参构造来初始化
    public EasyExcelListener(EasyexcelService easyexcelService){
        this.easyexcelService = easyexcelService;
    }

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    List<Easyexcel> list = new ArrayList<Easyexcel>();

    //这个监听器继承了AnalysisEventListener 就会首先调用这个方法，在这里面实现业务逻辑
    @Override
    public void invoke(Easyexcel easyexcel, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(easyexcel));
        list.add(easyexcel);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    //最后调用这个方法
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            easyexcelService.saveBatch(list);
        }
        log.info("存储数据库成功！");
    }

}
